import 'package:bike_ride/api/api_defines.dart';
import 'package:bike_ride/common/mvvm/base_page.dart';
import 'package:bike_ride/common/util/account_manager.dart';
import 'package:bike_ride/common/util/format.dart';
import 'package:bike_ride/common/util/hysize_fit.dart';
import 'package:bike_ride/common/widget/page_title_widget.dart';
import 'package:bike_ride/common/widget/rotate_arrow_widget.dart';
import 'package:bike_ride/model/freight/view_model/freight_vm.dart';
import 'package:bike_ride/generated/l10n.dart';
import 'package:bike_ride/res/style/color_styles.dart';
import 'package:bike_ride/res/style/theme_styles.dart';
import 'package:bike_ride/router/navigator_util.dart';
import 'package:bike_ride/router/routers.dart';
import 'package:flutter/material.dart';

///收费标准
class FreightView extends BaseStatefulPage<FreightViewModel> {
  ///vid\visible
  final Map<String,dynamic>? arguments;
  const FreightView({this.arguments, super.key});

  @override
  FreightViewState createState() => FreightViewState();
}

class FreightViewState
    extends BaseStatefulPageState<FreightView, FreightViewModel> {

  List<String> rotatedList = [];

  @override
  void initAttribute() {}

  @override
  void initObserver() {}

  void notifyChange() {
    if (mounted) {
      setState(() {});
    }
  }

  @override
  FreightViewModel viewBindingViewModel() {
    return FreightViewModel()..viewState = this;
  }

  @override
  Widget appBuild(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      backgroundColor: ColorStyles.color_F3F4F5,
      body: Column(
        children: [
          PageTitleWidget(title: S.current.chargeStandard),
          if(viewModel!.serverInfo != null)
            Expanded(
              child: Padding(
                padding: EdgeInsets.symmetric(
                    horizontal: ThemeStyles.pagePaddingHorizontal),
                child: SingleChildScrollView(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      if (viewModel!.serverInfo?.isRechargeBalance == 1 && (viewModel!.serverInfo?.minBalance??0) > 0)
                        _ItemWidget(
                          title: S.current.rechargeBeforeReturn,
                          price: '${viewModel!.serverInfo?.minBalance}${S.current.yuan}${S.current.up}',
                          desc: '${S.current.balanceOver}${viewModel!.serverInfo?.minBalance}${S.current.yuan}，${S.current.canUnlockToRide}',
                          children: [
                            TextButton(
                              onPressed: () {
                                if (!AccountManager.isLogin) {
                                  NavigatorUtil.push(context, Routers.loginView);
                                  return;
                                }
                                NavigatorUtil.push(context, Routers.walletView,arguments: {
                                  'show_charge_dialog': true,
                                }).then((value) {
                                  viewModel?.getBrandAreaInfo();
                                });
                              },
                              style: ButtonStyle(
                                backgroundColor: MaterialStateProperty.all<Color>(Colors.blue),
                                padding: MaterialStateProperty.all<EdgeInsets>(const EdgeInsets.symmetric(horizontal: 12, vertical: 8)),
                                shape: MaterialStateProperty.all<RoundedRectangleBorder>(
                                  RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(4),
                                  ),
                                ),
                              ),
                              child: Text(
                                S.current.toRecharge,
                                style: const TextStyle(color: Colors.white),
                              ),
                            ),
                          ],
                        ),
                      if(viewModel!.serverInfo?.isOpenDepositFreeCards == 1)
                        _ItemWidget(
                          title: S.current.rideByDepositCard,
                          desc: S.current.buyDepositCardTips,
                          children: [
                            TextButton(
                              onPressed: () {
                                if (!AccountManager.isLogin) {
                                  NavigatorUtil.push(context, Routers.loginView);
                                  return;
                                }
                                //跳转到购买免押卡
                              },
                              style: ButtonStyle(
                                backgroundColor: MaterialStateProperty.all<Color>(Colors.blue),
                                padding: MaterialStateProperty.all<EdgeInsets>(const EdgeInsets.symmetric(horizontal: 12, vertical: 8)),
                                shape: MaterialStateProperty.all<RoundedRectangleBorder>(
                                  RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(4),
                                  ),
                                ),
                              ),
                              child: Text(
                                S.current.toBuy,
                                style: const TextStyle(color: Colors.white),
                              ),
                            ),
                          ],
                        ),
                      if ((viewModel!.serverInfo?.useFreeTimeSec != 1 && (viewModel!.serverInfo?.freeTimeSec??0) > 0) || (viewModel!.serverInfo?.useFreeTimeSec == 1 && (viewModel!.serverInfo?.freeTimeSec??0) > 0))
                        _ItemWidget(
                          title: S.current.reliefReturn,
                          price: viewModel!.serverInfo?.useFreeTimeSec == 1 ? '${viewModel!.serverInfo?.freeTimeSec}${S.current.second}' : '${viewModel!.serverInfo?.freeTime}${S.current.mins}',
                          desc: '${S.current.freightTips1}${viewModel!.serverInfo?.useFreeTimeSec == 1 ? '${viewModel!.serverInfo?.freeTimeSec}${S.current.second}' : '${viewModel!.serverInfo?.freeTime}${S.current.mins}'}${S.current.freightTips2}',
                          children: [
                            Text(
                              '${S.current.freeTime}${(viewModel!.serverInfo?.freeRidingTimesEveryDay??0) > 0 ? ' (${S.current.freeDaily}${viewModel!.serverInfo?.freeRidingTimesEveryDay}${S.current.times})' : ''}',
                              style: const TextStyle(fontSize: 14),
                            ),
                          ],
                        ),
                      _ItemWidget(
                        title: S.current.rideFee,
                        price: '${viewModel!.startInfo['price']}${S.current.yuan}${S.current.up}',
                        children: [
                          if (viewModel!.billingPriceInfo.isNotEmpty || viewModel!.weekendPriceInfo.isNotEmpty)
                            Text(
                              S.current.commonChargeRange,
                              style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                            ),
                          _buildRow('${S.current.startAmount} (${viewModel!.startInfo['time']}${S.current.mins})','${viewModel!.startInfo['price']}${S.current.yuan}'),

                          _buildRow('${S.current.timeFee} (${S.current.over}${viewModel!.startInfo['time']}${S.current.mins})', '${viewModel!.timeInfo['price']}${S.current.yuan}/${viewModel!.timeInfo['time']}${S.current.mins}',),

                          Text(
                            '${S.current.noEnough}${viewModel!.timeInfo['time']}${S.current.mins}${S.current.as}${viewModel!.timeInfo['time']}${S.current.mins}${S.current.chargeFee}',
                            style: descTextStyle,
                          ),
                          for (var info in viewModel!.billingPriceInfo)
                            _RangeBox(
                              title: '${S.current.chargeRange}: ${info['billing_start_time']}~${info['billing_end_time']}',
                              startAmount: '${info['start_second'] ~/ 60}${S.current.mins}',
                              startPrice: '${formatMoney(info['start_price'])}${S.current.yuan}',
                              timeFee: '${info['billing_duration'] ~/ 60}${S.current.mins}',
                              timePrice: '${formatMoney(info['billing_price'])}${S.current.yuan}/${info['billing_duration'] ~/ 60}${S.current.mins}',
                              desc: '${S.current.noEnough}${info['billing_duration'] ~/ 60}${S.current.mins}${S.current.as}${info['billing_duration'] ~/ 60}${S.current.mins}${S.current.chargeFee}',
                            ),
                          for (var info in viewModel!.weekendPriceInfo)
                            _RangeBox(
                              title: '${info['billing_name']}${info['week_day']?.isNotEmpty ?? false ? ' (${info['week_day']?.map((item) => [S.current.sunday, S.current.monday, S.current.tuesday, S.current.wednesday, S.current.thursday, S.current.friday, S.current.saturday][item]).join('、')})' : ''}',
                              startAmount: '${info['start_second'] ~/ 60}${S.current.mins}',
                              startPrice: '${formatMoney(info['start_price'])}${S.current.yuan}',
                              timeFee: '${info['billing_duration'] ~/ 60}${S.current.mins}',
                              timePrice: '${formatMoney(info['billing_price'])}${S.current.yuan}/${info['billing_duration'] ~/ 60}${S.current.mins}',
                              desc: '${S.current.noEnough}${info['billing_duration'] ~/ 60}${S.current.mins}${S.current.as}${info['billing_duration'] ~/ 60}${S.current.mins}${S.current.chargeFee}',
                              isWeekend: info['billing_name']?.contains(S.current.restDay) ?? false,
                            ),
                          Padding(padding: EdgeInsets.symmetric(vertical: 10.rpx),child: const Divider(color: ColorStyles.color_F3F4F5,),),
                          _buildTips(S.current.ridingChargeTips1),
                          _buildTips(S.current.ridingChargeTips2),
                          _buildTips(S.current.ridingChargeTips3),
                        ],
                      ),
                      _ItemWidget(
                        title: S.current.violationFee,
                        price: '${formatMoney(viewModel!.serverInfo?.trafficFare)}${S.current.yuan}${S.current.up}',
                        children: [
                          if ((viewModel!.serverInfo?.trafficFare??0) > 0)
                            ViolationItem(
                              iconUrl: '${RequestConfig.imgServer}/images/assets/common/icon_violation_fee1.png',
                              title: S.current.parkAreaRule,
                              desc: '${S.current.parkAreaRuleTips}${formatMoney(viewModel!.serverInfo!.trafficFare)}${S.current.yuan}',
                              descGrey: S.current.parkAreaRuleTipsTo,
                            ),
                          if ((viewModel!.serverInfo?.serviceOutwardFee??0) > 0)
                            ViolationItem(
                              iconUrl: '${RequestConfig.imgServer}/images/assets/common/icon_violation_fee2.png',
                              title: S.current.operationAreaRule,
                              desc: '${S.current.operationAreaRuleTips}${formatMoney(viewModel!.serverInfo?.serviceOutwardFee)}${S.current.yuan}',
                              descGrey: S.current.operationAreaRuleTipsTo,
                            ),
                          if ((viewModel!.serverInfo?.nostopOutwardFee??0) > 0)
                            ViolationItem(
                              iconUrl: '${RequestConfig.imgServer}/images/assets/common/icon_violation_fee3.png',
                              title: S.current.forbiddenAreaRule,
                              desc: '${S.current.forbiddenAreaRuleTips}${formatMoney(viewModel!.serverInfo?.nostopOutwardFee)}${S.current.yuan}',
                              descGrey: S.current.forbiddenAreaRuleTipsTo,
                            ),
                          if ((viewModel!.serverInfo?.autoDeviceLockTime??0) > 0 || (viewModel!.serverInfo?.temporaryDeviceLockTime??0) > 0)
                            ViolationItem(
                              iconUrl: '${RequestConfig.imgServer}/images/assets/common/icon_violation_fee4.png',
                              title: S.current.autoBackBikeRule,
                              desc: [
                                if (viewModel!.serverInfo!.autoDeviceLockTime > 0)
                                  '${S.current.autoBackBikeRuleTips}${viewModel!.serverInfo!.autoDeviceLockTime ~/ 2}${S.current.mins}${S.current.autoBackBikeRuleTips2}',
                                if (viewModel!.serverInfo!.temporaryDeviceLockTime > 0)
                                  '${S.current.unlockTemp}${viewModel!.serverInfo!.temporaryDeviceLockTime}${S.current.mins}${S.current.autoBackBikeRuleTips2}',
                              ].join('\n'),
                              descGrey: S.current.autoBackBikeRuleTipsTo,
                            ),
                          if ((viewModel!.serverInfo?.isForceHelmet == 1 || viewModel!.serverInfo?.isNeedHelmet == 1) && (viewModel!.serverInfo?.helmetFee??0) > 0)
                            ViolationItem(
                              iconUrl: '${RequestConfig.imgServer}/images/assets/common/icon_violation_fee5.png',
                              title: S.current.helmetUseRule,
                              desc: '${S.current.helmetUseRuleTips}${formatMoney(viewModel!.serverInfo!.helmetFee)}${S.current.yuan}',
                              descGrey: S.current.helmetUseRuleTipsTo,
                            ),
                          if (viewModel!.serverInfo?.helmetFeeInfo?.openHelmetCheck == 1 && (viewModel!.serverInfo?.helmetFeeInfo?.unuseHelmetFee??0) > 0)
                            ViolationItem(
                              iconUrl: '${RequestConfig.imgServer}/images/assets/common/icon_violation_fee5.png',
                              title: S.current.helmetUseRule,
                              desc: '${S.current.helmetUseRuleTips2}${formatMoney(viewModel!.serverInfo!.helmetFeeInfo!.unuseHelmetFee)}${S.current.yuan}',
                              descGrey: S.current.helmetUseRuleTipsTo2,
                            ),
                        ],
                      ),
                      if ((viewModel!.serverInfo?.maxPrice??0) > 0)
                        _ItemWidget(
                          title: S.current.topAmount,
                          price: '${formatMoney(viewModel!.serverInfo?.maxPrice)}${S.current.yuan}',
                          desc: '${S.current.topAmountTips}${formatMoney(viewModel!.serverInfo?.maxPrice)}${S.current.yuan}。',
                          children: [
                            Text(
                              S.current.topAmount,
                              style: const TextStyle(fontSize: 14),
                            ),
                          ],
                        ),
                      ConstrainedBox(
                        constraints: BoxConstraints(minHeight: 80.rpx),
                        child: Text(
                          S.current.topAmountTipsTo,
                          style: descTextStyle,
                          textAlign: TextAlign.left,
                        ),
                      ),
                      SizedBox(height: 28.rpx,),
                    ],
                  ),
                ),
              ),
            ),
        ],
      ),
    );
  }

  Widget _buildTips(String tips){
    return ConstrainedBox(
      constraints: BoxConstraints(minHeight: 30.rpx),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          margin: EdgeInsets.only(right: 10.rpx,top: 18.rpx),
          width: 6.rpx,
          height: 6.rpx,
          decoration: const BoxDecoration(
            shape: BoxShape.circle,
            color: ColorStyles.color_999999,
          ),
        ),
        Expanded(child: Text(tips,style: descTextStyle,))
      ],
    ),);
  }

  Widget _buildRow(String left,String right){
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(
          left,
          style: TextStyle(fontSize: 26.rpx, color: ColorStyles.color_666666),
        ),
        Text(
          right,
          style: TextStyle(fontSize: 26.rpx, color: ColorStyles.color_666666),
        )
      ],
    );
  }

}

final descTextStyle = TextStyle(fontSize: 28.rpx,color: ColorStyles.color_999999);

class _ItemWidget extends StatefulWidget {
  final String title;
  final String? price;
  final String? desc;
  final List<Widget> children;
  const _ItemWidget({required this.title, this.price, this.desc, required this.children});

  @override
  State<_ItemWidget> createState() => _ItemWidgetState();
}

class _ItemWidgetState extends State<_ItemWidget> {
  final rotaKey = GlobalKey<RotateArrowWidgetState>();
  bool isRotated = false;

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 22.rpx,vertical: 24.rpx),
      margin: EdgeInsets.only(bottom: 20.rpx),
      decoration: BoxDecoration(
          color: ColorStyles.color_FFFFFF,
          borderRadius: BorderRadius.all(Radius.circular(16.rpx))
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: (){
              rotaKey.currentState?.rotate();
            },
            child: Row(
              children: [
                Text(
                  widget.title,
                  style: const TextStyle(fontWeight: FontWeight.bold),
                ),
                const Spacer(),
                Text(
                  widget.price ?? '',
                  style:  const TextStyle(fontWeight: FontWeight.bold),
                ),
                RotateArrowWidget(
                  key: rotaKey,
                  isRotate: isRotated,
                  onChange: (value) {
                    setState(() {
                      isRotated = value;
                    });
                  },
                )
              ],
            ),
          ),
          if (widget.children.isNotEmpty && isRotated)
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: widget.children,
            ),
          if (widget.desc != null && isRotated)
            Text(
              widget.desc!,
              style: descTextStyle,
            ),
        ],
      ),
    );
  }
}


class _RangeBox extends StatelessWidget {
  final String title;
  final String startAmount;
  final String startPrice;
  final String timeFee;
  final String timePrice;
  final String desc;
  final bool isWeekend;

  const _RangeBox({
    required this.title,
    required this.startAmount,
    required this.startPrice,
    required this.timeFee,
    required this.timePrice,
    required this.desc,
    this.isWeekend = false,
  });

  Widget _buildRow(String left,String right){
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(
          left,
          style: TextStyle(fontSize: 26.rpx, color: ColorStyles.color_666666),
        ),
        Text(
          right,
          style: TextStyle(fontSize: 26.rpx, color: ColorStyles.color_666666),
        )
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(padding: EdgeInsets.symmetric(vertical: 10.rpx),child: const Divider(color: ColorStyles.color_F3F4F5,),),

        Text(
          title,
          style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
        ),
        _buildRow('${S.current.startAmount}: ($startAmount)', startPrice,),
        _buildRow('${S.current.timeFee}: (${S.current.overed})', timePrice,),

        Text(
          desc,
          style: descTextStyle,
        ),
        if (isWeekend)
          Text(
            S.current.otherRule,
            style: const TextStyle(fontSize: 14, color: Colors.grey),
          ),
      ],
    );
  }
}


class ViolationItem extends StatelessWidget {
  final String iconUrl;
  final String title;
  final String desc;
  final String? descGrey;

  const ViolationItem({super.key,
    required this.iconUrl,
    required this.title,
    required this.desc,
    this.descGrey,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(bottom: 20.rpx),
      child: Row(
        children: [
          Image.network(iconUrl, width: 120.rpx, height: 120.rpx,fit: BoxFit.fill,),
          SizedBox(width: 28.rpx,),
          Flexible(child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                title,
                style: const TextStyle(fontWeight: FontWeight.bold),
              ),
              Text(desc),
              if (descGrey != null)
                Text(
                  descGrey!,
                  style: const TextStyle(color: Colors.grey),
                ),
            ],
          ))
        ],
      ),
    );
  }
}

class ExplainWidget extends StatelessWidget {
  final String title;
  final List<String> desc;

  const ExplainWidget({super.key,
    required this.title,
    required this.desc,
  });

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          title,
          style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
        ),
        for (var item in desc)
          Text(
            item,
            style: const TextStyle(fontSize: 14),
          ),
      ],
    );
  }
}